<?php

namespace App\Http\Controllers\group;

use App\Models\Commission;
use App\Models\GroupMember;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TeamController extends BaseController
{
    public function preview()
    {
        $userId = auth('jwt')->id();
        $memberIds = GroupMember::query()
            ->where('leader_id', $userId)
            ->select('user_id')
            ->pluck('user_id')
            ->toArray();

        $total = 0;
        $today = 0;
        $yesterday = 0;

        if (!empty($memberIds)) {
            $total = Commission::query()
                ->where('user_id', $userId)
                ->whereIn('child_user_id', $memberIds)
                ->sum('user_money');
            $today = Commission::query()
                ->where('user_id', $userId)
                ->whereIn('child_user_id', $memberIds)
                ->whereDate('child_user_withdraw_at', Carbon::today())
                ->sum('user_money');
            $yesterday = Commission::query()
                ->where('user_id', $userId)
                ->whereIn('child_user_id', $memberIds)
                ->whereDate('child_user_withdraw_at', Carbon::yesterday())
                ->sum('user_money');
        }

        return $this->success([
            'total' => $total,
            'today' => $today,
            'yesterday' => $yesterday,
        ]);
    }

    public function detail(Request $request)
    {
        $userId = auth('jwt')->id();
        $memberIds = GroupMember::query()
            ->where('leader_id', $userId)
            ->select('user_id')
            ->pluck('user_id')
            ->toArray();
        $sql = <<<SQL
select
users.uuid, users.nickname, sum(user_money)as total, date(child_user_withdraw_at) as date
from commissions
left join users on users.id = commissions.child_user_id
where child_user_id in (%s) group by date(child_user_withdraw_at), child_user_id;
SQL;
        $list = DB::select(sprintf($sql, implode(',', $memberIds)));

        return $this->success($list);
    }
}
